﻿using DataAccess;
using DTO;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAO
{
    public class PhieuThuTienDAO
    {
        public static string TaoMaPhieuThu()
        {
            String strChu = "PT";
            String strSo = "0";
            String strMaDau = "PT001";

            String strSql = "SELECT TOP 1 MaPhieuThu FROM PHIEUTHU ORDER BY MaPhieuThu DESC";

            try
            {
                String strMaCuoi = DataConnection.ExecScalar(strSql).ToString();
                String strTemp = ((int.Parse(strMaCuoi.Remove(0, 2)) + 1)).ToString();
                String strMaNhanVien = strChu;
                while (strMaNhanVien.Length + strTemp.Length < 5)
                    strMaNhanVien += strSo;
                return strMaNhanVien + strTemp;

            }
            catch (Exception)
            {
                return strMaDau;
            }
        }
        public static bool ThemPhieuThu(PhieuThuTienDTO pt)
        {
            string query = "INSERT INTO PHIEUTHU (MaPhieuThu,MaDaiLy,SoTienThu,NgayThuTien) VALUES('" + pt.MaPhieuThu + "','" + pt.MaDaiLy + "','" + pt.SoTienThu + "','" + pt.NgayThuTien + "')";
            try
            {
                DataConnection.ExecNonQuery(query);
                return true;
            }
            catch(System.Exception e)
            {
                Console.WriteLine("not access database",e.Message);
                return false;
            };

        }


        public static List<PhieuThuTienDTO> LoadDanhDanhSachPhieuThu()
        {
            List<PhieuThuTienDTO> list = new List<PhieuThuTienDTO>();
            string query = "SELECT * FROM PHIEUTHU ";
            DataTable dt = DataConnection.ExecQuery(query);
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow dr = dt.Rows[i];
                    PhieuThuTienDTO dl = new PhieuThuTienDTO();
                    dl.MaPhieuThu = dr["MaPhieuThu"].ToString();
                    dl.MaDaiLy = dr["MaDaiLy"].ToString();
                    dl.NgayThuTien = dr["NgayThuTien"].ToString();
                    dl.SoTienThu = Convert.ToInt32(dr["SoTienThu"]);
                    list.Add(dl);
                }
            }
            return list;
        }

        public static bool deletePhieuThu(string MaPhieuThu)
        {
            string query = "DELETE PHIEUTHU WHERE MaPhieuThu = '" + MaPhieuThu + "'";
            try
            {
                DataConnection.ExecQuery(query);
                return true;
            }
            catch (System.Exception e)
            {
                Console.WriteLine("Not access to database:{0}", e.Message);
                return false;
            }
        }
    }
}
